import { Routes, Route } from 'react-router-dom'
import { useEffect } from 'react'
import HomePage from './pages/HomePage'
import TaskCreatePage from './pages/TaskCreatePage'
import TaskDetailPage from './pages/TaskDetailPage'
import SearchPage from './pages/SearchPage'
import StatsPage from './pages/StatsPage'
import ProfilePage from './pages/ProfilePage'
import SettingsPage from './pages/SettingsPage'
import RecurringTasksPage from './pages/RecurringTasksPage'
import RecurringTaskEditPage from './pages/RecurringTaskEditPage'
import RecurringTaskInstancesPage from './pages/RecurringTaskInstancesPage'
import KanbanPage from './pages/KanbanPage'
import NotificationPage from './pages/NotificationPage'
import NotificationTestPage from './pages/NotificationTestPage'
import HelpPage from './pages/HelpPage'
import SmartParseTestPage from './pages/SmartParseTestPage'
import LoginPage from './pages/LoginPage'
import RegisterPage from './pages/RegisterPage'
import ChatPage from './pages/ChatPage'
import Layout from './components/Layout'
import ProtectedRoute from './components/ProtectedRoute'
import { AuthProvider } from './contexts/AuthContext'
import { useNotifications } from './hooks/useNotifications'
import { useToast } from './hooks/useToast'
import { ToastContainer } from './components/Toast'
import PWAInstallPrompt from './components/PWAInstallPrompt'
import { authAPI } from './services/authAPI'

function App() {
  const { permission, isEnabled } = useNotifications()
  const { toasts, removeToast } = useToast()

  useEffect(() => {
    // 应用启动时的通知初始化
    console.log('AIDE 应用已启动')
    console.log('通知权限状态:', permission)
    console.log('通知功能启用:', isEnabled)

    // 如果是首次访问且未设置权限，可以在适当时机提示用户
    if (permission === 'default') {
      // 延迟一段时间后提示，避免过于突兀
      setTimeout(() => {
        console.log('可以在合适的时机提示用户启用通知功能')
      }, 5000)
    }

    // 设置Service Worker消息处理
    const handleServiceWorkerMessage = (event: MessageEvent) => {
      if (event.data.type === 'GET_AUTH_TOKEN') {
        const token = authAPI.getToken()
        event.ports[0].postMessage({ token })
      }
    }

    // 通知Service Worker客户端已激活
    const notifyServiceWorkerActive = () => {
      if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
        navigator.serviceWorker.controller.postMessage({
          type: 'CLIENT_ACTIVE'
        })
      }
    }

    // 页面卸载时通知Service Worker客户端不活跃
    const handleBeforeUnload = () => {
      if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
        navigator.serviceWorker.controller.postMessage({
          type: 'CLIENT_INACTIVE'
        })
      }
    }

    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.addEventListener('message', handleServiceWorkerMessage)
      
      // 通知Service Worker应用已启动
      notifyServiceWorkerActive()
      
      // 监听页面卸载
      window.addEventListener('beforeunload', handleBeforeUnload)
      
      // 清理函数
      return () => {
        navigator.serviceWorker.removeEventListener('message', handleServiceWorkerMessage)
        window.removeEventListener('beforeunload', handleBeforeUnload)
      }
    }
  }, [permission, isEnabled])

  return (
    <AuthProvider>
      <Routes>
        {/* 公开路由 */}
        <Route path="/login" element={<LoginPage />} />
        <Route path="/register" element={<RegisterPage />} />
        
        {/* 受保护的路由 */}
        <Route path="/*" element={
          <ProtectedRoute>
            <Layout>
              <Routes>
                <Route path="/" element={<HomePage />} />
                <Route path="/create" element={<TaskCreatePage />} />
                <Route path="/smart-parse-test" element={<SmartParseTestPage />} />
                <Route path="/task/:id" element={<TaskDetailPage />} />
                <Route path="/search" element={<SearchPage />} />
                <Route path="/stats" element={<StatsPage />} />
                <Route path="/kanban" element={<KanbanPage />} />
                <Route path="/profile" element={<ProfilePage />} />
                <Route path="/settings" element={<SettingsPage />} />
                <Route path="/notifications" element={<NotificationPage />} />
                <Route path="/notifications/test" element={<NotificationTestPage />} />
                <Route path="/help" element={<HelpPage />} />
                <Route path="/chat" element={<ChatPage />} />
                <Route path="/recurring" element={<RecurringTasksPage />} />
                <Route path="/recurring/:id/edit" element={<RecurringTaskEditPage />} />
                <Route path="/recurring/:id/instances" element={<RecurringTaskInstancesPage />} />
              </Routes>
            </Layout>
          </ProtectedRoute>
        } />
      </Routes>
      
      {/* Toast 通知容器 */}
      <ToastContainer toasts={toasts} onClose={removeToast} />
      
      {/* PWA 安装提示 */}
      <PWAInstallPrompt />
    </AuthProvider>
  )
}

export default App
